﻿using GFluentCode.Entity;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;

namespace GFluentCode.ORM.SqlServer
{
    /// <summary>
    /// SqlServer系统表操作
    /// </summary>
    public class SqliteORM : GFluentORMBase<GFluentTableEntity>
    {
        public SqliteORM(string conn) : base(conn, EnDbType.Sqlite) { }

        /// <summary>
        /// 查询系统表名
        /// </summary>
        /// <returns></returns>
        public IList<GFluentTableNameEntity> QueryTableNames()
        {
            return QueryBySql<GFluentTableNameEntity>(@"
select name TableName,'' SchemaName from sqlite_master where type='table' order by name");
        }

        /// <summary>
        /// 获取表对象
        /// </summary>
        /// <param name="tableName"></param>
        /// <returns></returns>
        public GFluentTableEntity QueryTableEntity(string tableName)
        {
            var dt = QueryDataTableBySql($"PRAGMA table_info({tableName})");

            List<GFluentColumnEntity> cols = new List<GFluentColumnEntity>();

            foreach(DataRow dr in dt.Rows)
            {
                var col = new GFluentColumnEntity
                {
                    TableName = tableName,
                    ColumnName = dr["name"].ToString(),
                    ColumnType=dr["type"].ToString()
                };

                cols.Add(col);
            }

            return new GFluentTableEntity { TableName = tableName, Columns = cols };
        }

        /// <summary>
        /// 获取表对象
        /// </summary>
        public IList<GFluentTableEntity> QueryTableEntitys(params string[] tableNames)
        {
            var r = new List<GFluentTableEntity>();

            foreach (var tn in tableNames)
                r.Add(QueryTableEntity(tn));

            return r;
        }
    }
}
